package csv;

import java.util.ArrayList;
import java.util.Iterator;

public class CSVFile
{
  private final String[] columnNames;
  private final ArrayList<String[]> table;

  public CSVFile(String[] columnNames)
  {
    this.columnNames = columnNames;
    this.table = new ArrayList();
  }

  public void addRow(String[] input) throws CSVFile.InvalidRowException {
    if (input.length != this.columnNames.length)
      throw new InvalidRowException();
    this.table.add(input);
  }

  public void removeRow(int index) {
    this.table.remove(index);
  }

  public int amountOfRows() {
    return this.table.size();
  }

  public boolean isEmpty() {
    return this.table.isEmpty();
  }

  public String[] getRow(int index) {
    return (String[])this.table.get(index);
  }

  public boolean contains(String[] strings) {
    return this.table.contains(strings);
  }

  public String[] getAndRemoveRow(int index) {
    String[] result = getRow(index);
    removeRow(index);
    return result;
  }

  public Iterator<String[]> getRowIterator() {
    return this.table.iterator();
  }

  public String[] getFirst(String columnName, String value) {
    for (int i = 0; i < this.columnNames.length; i++)
      if (this.columnNames[i].equals(columnName))
        return getFirst(i, value);
    return null;
  }

  public String[] getFirst(int columnNumber, String value) {
    Iterator it = getRowIterator();
    while (it.hasNext()) {
      String[] currentRow = (String[])it.next();
      if (currentRow[columnNumber].trim().equals(value))
        return currentRow;
    }
    return null;
  }

  public class InvalidRowException extends RuntimeException
  {
    private static final long serialVersionUID = 1L;

    public InvalidRowException()
    {
    }
  }
}